package com.lottery.material.controller.admin.promotion;

import com.lottery.material.common.EnumInfo;
import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.enumeration.common.CommonEnum;
import com.lottery.material.pojo.page.Page;
import com.lottery.material.pojo.page.PageData;
import com.lottery.material.pojo.promotion.PromotionFeeConfig;
import com.lottery.material.pojo.promotion.PromotionRuleConfig;
import com.lottery.material.pojocustom.promotion.PromotionFeeConfigCustom;
import com.lottery.material.pojocustom.promotion.PromotionRuleConfigCustom;
import com.lottery.material.service.admin.promotion.PromotionFeeConfigService;
import com.lottery.material.service.admin.promotion.PromotionRuleConfigService;
import com.lottery.material.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Description：推广收费配置Controller
 * Created by 朱正磊 on 2019-04-13 20:22
 */
@Controller("adminPromotionFeeConfigController")
@RequestMapping("/admin/promotionFeeConfig")
public class PromotionFeeConfigController extends BaseController {

    //菜单地址，用于权限控制
    private String menuUrl = "admin/promotionFeeConfig/list";

    private final PromotionFeeConfigService promotionFeeConfigService;

    private final PromotionRuleConfigService promotionRuleConfigService;

    @Autowired
    public PromotionFeeConfigController(PromotionFeeConfigService promotionFeeConfigService,
                                        PromotionRuleConfigService promotionRuleConfigService) {
        this.promotionFeeConfigService = promotionFeeConfigService;
        this.promotionRuleConfigService = promotionRuleConfigService;
    }

    /**
     * description：分页列表
     * user 朱正磊
     * time 2019-04-17 15:06
     * @param page 分页对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/list")
    public ModelAndView listPage(Page page, Map<String, Object> map) {
        //分页对象设置页面请求参数
        PageData pd = getPageData();
        PdUtil.rePut(pd);
        page.setPd(pd);

        //查询分页列表
        List<PromotionFeeConfigCustom> list = promotionFeeConfigService.findCustomListPage(page);
        map.put("list", list);
        map.put("pd", pd);
        map.put("QX", Jurisdiction.getHC());

        return new ModelAndView("promotion/promotionFeeConfig/listPage", map);
    }

    /**
     * description：详情页面
     * user 朱正磊
     * time 2019-04-17 16:20
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/detailPage")
    public ModelAndView detailPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {//判断是否有查看权限
            return null;
        }

        //根据主键查询扩展类
        PromotionFeeConfigCustom promotionFeeConfig = promotionFeeConfigService.findCustomById(id);
        map.put("promotionFeeConfig", promotionFeeConfig);

        return new ModelAndView("promotion/promotionFeeConfig/detailPage", map);
    }

    /**
     * description：添加页面
     * user 朱正磊
     * time 2019-04-17 16:26
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/addPage")
    public ModelAndView addPage(Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {//判断是否有添加权限
            return null;
        }

        //推广规则配置列表
        List<PromotionRuleConfigCustom> promotionRuleConfigList = promotionRuleConfigService.findAll();
        map.put("promotionRuleConfigList", promotionRuleConfigList);

        //添加请求地址
        map.put("actionUrl", "admin/promotionFeeConfig/add");

        return new ModelAndView("promotion/promotionFeeConfig/editPage", map);
    }

    /**
     * description：添加
     * user 朱正磊
     * time 2019-04-17 16:39
     * @param promotionFeeConfig 对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/add")
    public ModelAndView add(PromotionFeeConfig promotionFeeConfig, Map<String, Object> map) {
        Integer flag = promotionFeeConfigService.add(promotionFeeConfig);
        if (Objects.equals(flag, 0)) { //添加失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：修改页面
     * user 朱正磊
     * time 2019-04-17 16:48
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/editPage")
    public ModelAndView editPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }

        //根据主键查询扩展类
        PromotionFeeConfigCustom promotionFeeConfig = promotionFeeConfigService.findCustomById(id);
        map.put("promotionFeeConfig", promotionFeeConfig);

        //推广规则配置列表
        List<PromotionRuleConfigCustom> promotionRuleConfigList = promotionRuleConfigService.findAll();
        map.put("promotionRuleConfigList", promotionRuleConfigList);

        //修改请求地址
        map.put("actionUrl", "admin/promotionFeeConfig/edit");

        return new ModelAndView("promotion/promotionFeeConfig/editPage", map);
    }

    /**
     * description：修改
     * user 朱正磊
     * time 2019-04-17 16:58
     * @param promotionFeeConfig 对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/edit")
    public ModelAndView edit(PromotionFeeConfig promotionFeeConfig, Map<String, Object> map) {
        Integer flag = promotionFeeConfigService.updateById(promotionFeeConfig);
        if (Objects.equals(flag, 0)) { //修改失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：根据主键删除一条数据（逻辑删除）
     * user 朱正磊
     * time 2019-04-30 11:26
     * @param id 主键
     * @return 返回响应对象
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseResult delete(Integer id) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {//判断是否有删除权限
            return null;
        }
        Integer flag = promotionFeeConfigService.deleteLogicById(id);
        if (Objects.equals(0, flag)) {
            return ResponseResult.buildResult(400, "删除失败！");
        } else {
            return ResponseResult.buildResult(200, "删除成功！");
        }
    }

    /**
     * description：验证推广金额不能重复（根据推广规则）
     * user 朱正磊
     * time 2019-05-15 11:00
     * @param request 请求对象
     * @return 返回响应对象
     */
    @RequestMapping("/validateSameAmount")
    @ResponseBody
    public ResponseResult validateSameAmount(HttpServletRequest request) {
        String idStr = request.getParameter("id");//主键
        String amount = request.getParameter("chargeAmount");//推广金额
        amount = amount.trim();//去两端空格
        Integer chargeAmount = Integer.valueOf(amount);
        Integer id = null;
        if (AssertUtil.isNotEmpty(idStr)) {//修改
            id = Integer.valueOf(idStr);
        }
        Integer promotionRuleId = Integer.valueOf(request.getParameter("promotionRuleId"));//推广规则
        List<PromotionFeeConfig> promotionFeeConfigList = promotionFeeConfigService.selectByChargeAmount(id, chargeAmount, promotionRuleId);
        Integer size = promotionFeeConfigList.size();//数据个数（1个表示已存在相同推广金额的数据，0个则表示不存在）
        if (Objects.equals(size, 1)) {
            return ResponseResult.buildResult(400, "该推广规则下该推广金额已存在，请填写其他推广金额！");
        }
        return ResponseResult.buildResult(200);
    }

    /**
     * description：验证是否允许逻辑删除数据（根据推广规则）
     * 如果只剩一个推广收费配置，那么不允许删除，要想删除该条数据必须再新增一条数据，因为至少要保留一条配置数据
     * user 朱正磊
     * time 2019-05-15 14:14
     * @param id 主键
     * @return 返回响应对象
     */
    @RequestMapping("/validateDelete")
    @ResponseBody
    public ResponseResult validateDelete(Integer id) {
        PromotionFeeConfig promotionFeeConfig = promotionFeeConfigService.findById(id);
        Integer promotionRuleId = promotionFeeConfig.getPromotionRuleId();//推广规则ID
        List<PromotionFeeConfig> promotionFeeConfigList = promotionFeeConfigService.selectNotBeDeleted(promotionRuleId);
        Integer size = promotionFeeConfigList.size();
        if (Objects.equals(size, 1)) {//只剩一条数据
            return ResponseResult.buildResult(400, "要想删除该条数据必须再新增一条数据，因为一个推广规则下面至少要保留一条配置数据！");
        }
        return ResponseResult.buildResult(200);
    }

    /**
     * description：验证是否允许新增和修改数据，
     * 如果已经新增了6条推广收费配置数据，那么就不再允许新增新的推广收费配置；
     * 在修改的时候，如果修改了推广规则，而相应的推广规则下面已经有了6条推广收费配置数据，那么就提示不允许修改！
     * user 朱正磊
     * time 2019-05-15 14:38
     * @param request 请求对象
     * @return 返回响应对象
     */
    @RequestMapping("/validateAdd")
    @ResponseBody
    public ResponseResult validateAdd(HttpServletRequest request) {
        String id = request.getParameter("id");
        if (AssertUtil.isNotEmpty(id)) {//修改
            Integer paramId = Integer.valueOf(id);//请求id
            PromotionFeeConfig config = promotionFeeConfigService.findById(paramId);
            //数据库保存的推广规则ID
            Integer dataPromotionRuleId = config.getPromotionRuleId();
            //页面请求的推广规则ID
            Integer paramPromotionRuleId = Integer.valueOf(request.getParameter("promotionRuleId"));
            if (Objects.equals(dataPromotionRuleId, paramPromotionRuleId)) {//没有修改推广规则
                return ResponseResult.buildResult(200);
            }
            List<PromotionFeeConfig> promotionFeeConfigList = promotionFeeConfigService.selectNotBeDeleted(paramPromotionRuleId);
            Integer size = promotionFeeConfigList.size();
            if (Objects.equals(size, 6)) {//想要修改成的推广规则已经有了6条未逻辑删除的数据
                return ResponseResult.buildResult(400, "该推广规则下已经有了6条推广收费配置数据，不允许修改成该推广规则！");
            }
        }
        Integer promotionRuleId = Integer.valueOf(request.getParameter("promotionRuleId"));//推广规则ID
        List<PromotionFeeConfig> promotionFeeConfigList = promotionFeeConfigService.selectNotBeDeleted(promotionRuleId);
        Integer size = promotionFeeConfigList.size();
        if (Objects.equals(size, 6)) {//之前已经新增了6条未逻辑删除的数据
            return ResponseResult.buildResult(400, "该推广规则之前已经新增了6条推广收费配置数据，不再允许新增新的推广收费配置！");
        }
        return ResponseResult.buildResult(200);
    }

}
